package JDOM;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import DOM.ReadXMLDOM;

public class ModifyXMLFile {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Reading staff.xml");
		String xmlFileName=ReadXMLDOM.class.getResource("../resources/staff.xml").getPath();
		
		try{
			SAXBuilder builder = new SAXBuilder();
			File xmlFile = new File(xmlFileName);
			
			Document doc=(Document)builder.build(xmlFile);
			Element rootnode=doc.getRootElement();
			
			Random rand=new Random( (new Date()).getSeconds() );
			System.out.println(rand.nextInt(10));
			
			
			Element newElem=new Element("staff").setAttribute("id", rand.nextInt(10)+"");
			Element firstname=new Element("firstname").setText(rand.nextInt(10)+"");
			Element lastname=new Element("lastname").setText(rand.nextInt(10)+"");
			Element nickname=new Element("nickname").setText(rand.nextInt(10)+"");
			Element salary=new Element("salary").setText(rand.nextInt(10)+"");
			
			newElem.addContent(firstname).addContent(lastname).addContent(nickname).addContent(salary);
			
			rootnode.addContent(newElem);
			
			XMLOutputter xmlOutput=new XMLOutputter();
			xmlOutput.setFormat(Format.getPrettyFormat());
			xmlOutput.output(doc, new FileWriter(xmlFileName));
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			System.out.println("finally");
		}
		
	}

}
